from flask import current_app, jsonify
from sqlalchemy import desc

from apps.extention.models.cidata import CiProject
from apps.extention.utils.gitlab_client import GitlabClient
from apps.extention.utils.jenkins_client import JenkinsClient
from library.api.db import db
from library.api.transfer import transfer2json


class CiProjectBusiness(object):

    @classmethod
    def _query(cls):
        return CiProject.query.add_columns(
            CiProject.id.label('id'),
            CiProject.name.label('name'),
            CiProject.git_url.label('git_url'),
            CiProject.project_type.label('project_type'),
            CiProject.exclusions.label('exclusions'),
            CiProject.deploy_module_name.label('module_name'),
            CiProject.project_members.label('project_members'),
            CiProject.dingding.label('dingding')
        )

    @classmethod
    @transfer2json(
        '?id|!name|!url|!git_url|!project_type|!exclusions|!module_name|!project_members|!dingding')
    def query_all_json(cls):
        return cls._query().filter(CiProject.status == CiProject.ACTIVE).order_by(desc(CiProject.id)).all()

    @classmethod
    def create_project(cls, name, url, git_project_id, project_type, module_name, members, exclusions, dingding):
        project_data = cls._query().filter(CiProject.git_project_id == git_project_id,
                                           CiProject.deploy_module_name == module_name,
                                           CiProject.status == CiProject.ACTIVE).all()
        git_client = GitlabClient(url)
        git_data = git_client.get_project()
        if git_data['status'] == 1:
            return 102, '', {'msg': '获取gitlab信息出错', 'status': 0}
        if git_data['id'] != git_project_id:
            return 102, '', {'msg': 'git_project_id与gitlab信息不一致', 'status': 0}
        if len(project_data) > 0:
            return 103, '', {'msg': '项目名字重复', 'status': 0}
        ci_pipeline = cls._query().filter(CiProject.git_project_id == git_project_id).all()
        uid = ''
        if len(ci_pipeline) == 0:
            uid = JenkinsClient.create_job(url, '', name, 'pipeline', dingding)  # 创建job
            # todo: 更新gitlab hook
        else:
            for i in ci_pipeline:
                uid = i.git_hook_token
                break
        try:
            ci_project = CiProject(
                name=name,
                git_url=url,
                git_hook_token=uid,
                git_project_id=git_project_id,
                project_type=project_type,
                deploy_module_name=module_name,
                dingding=dingding,
                members=members,
                exclusions=exclusions
            )
            db.session.add(ci_project)
            db.session.commit()

            return 0, None
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(str(e))
            return 102, str(e)

    @classmethod
    def modify_project(cls, id, module_name, members, exclusions, dingding):
        try:
            ci_project = CiProject.query.get(id)
            ci_project.deploy_module_name = module_name
            ci_project.members = members
            ci_project.exclusions = exclusions
            ci_project.dingding = dingding
            db.session.add(ci_project)
            db.session.commit()
            return 0, None
        except Exception as e:
            current_app.logger.error(str(e))
            return 102, str(e)
